#include "../include/Game.hpp"

Game &Game::Singleton(){
    static Game game;
    return game;
}

inline void Game::set_loop(){
    current_state = next_state;
    ++ frameCount;
    lastCallTime = chrono::steady_clock::now();
}

void Game::delay_fps(int fps){
    int idealDuration = 1000 / fps;
    int loopDuration = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - lastCallTime).count();
    if(loopDuration < idealDuration)
        Sleep(idealDuration - loopDuration);
}

void Game::initialize(){
    // 打开CMD颜色
    system((GameConfiguration::PATH_TO_ANSICON + "-i").c_str());
    system((GameConfiguration::PATH_TO_ANSICON + "-l").c_str());
    // 设置光标
    setCursorHide();
}

void Game::update(){
    if(current_state.controlState == GameState::ControlState::MAINMENU){
        if(GetAsyncKeyState(VK_RETURN)){
            // 选择
        } else if(GetAsyncKeyState(VK_ESCAPE)){
            // 退出
            next_state.controlState = GameState::ControlState::NULLSTATE;
            next_state.stateValue = GameState::EXITING_NORMAL;
        } else if(GetAsyncKeyState(VK_UP)){
            // 用于菜单选择的上键盘
        } else if(GetAsyncKeyState(VK_DOWN)){
            // 用于菜单选择的下键盘
        }
    } else if(current_state.controlState == GameState::ControlState::INGAME){
        if(current_state.stateValue == GameState::GAMEINIT){
            generate_map();
        } else if(current_state.stateValue == GameState::GAMERUN){
            move_snake();
            update_snake();
            late_update_snake();
        } else if(current_state.stateValue == GameState::GAMEEND){
            next_state.controlState = GameState::ControlState::SCOREBOARD;
        }
    }
}

void Game::lateUpdate(){
}


void Game::draw(){

    // 绘制地图部分
    paintScreen(drawEffects, mmap);
}

void Game::end(){
    setCursorShow();
    system((GameConfiguration::PATH_TO_ANSICON + "-u").c_str());
}

void paintScreen(DrawEffects drawEffects, const Map &mmap){
    if(drawEffects & DRAW_REVERSE_BACKFRONT)
        setReverseOn();

    for(int i = 0; i < MAP_SIZE_X; i++){
        for(int j = 0; j < MAP_SIZE_Y; j++)
            drawCharacter();
    }


    if(drawEffects & DRAW_REVERSE_BACKFRONT)
        setReverseOff();
}